package com.hj.ct;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings.Secure;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import com.baidu.mapapi.SDKInitializer;
import com.hj.ct.activity.StartActivity;
import com.hj.ct.logic.BaseLogic.OnHandlerResponse;
import com.hj.ct.logic.GatherDataLogic;
import com.hj.ct.logic.LoginLogic;
import com.hj.ct.util.CrashHandler;
import com.hj.ct.util.LogF;
import com.hj.ct.util.SDcardUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class App extends Application {

	public static App app;
	public static String IMEI;
	public static String IMSI;
	public static String LANG;
	public static String CARI;
	public static String NET;
	public static String SCWH;
	public static final String PREFS_FILE = "quit_share_udid.xml";
	public static final String PREFS_DEVICE_ID = "quit_share_device_id";
	public static String UDID;
	private HashMap<String, Object> appCache = new HashMap<String, Object>();
	private String TAG = App.class.getSimpleName();

	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		app = this;
		SDKInitializer.initialize(getApplicationContext());
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		IMEI = tm.getDeviceId();
		IMSI = tm.getSubscriberId();
		LANG = getResources().getConfiguration().locale.getLanguage();
		CARI = tm.getSimOperatorName();
		NET = getAPNType();
		SCWH = getHW();
		getUDID();
		// 异常处理，不需要处理时注释掉这两句即可！
		CrashHandler crashHandler = CrashHandler.getInstance();
		// 注册crashHandler
		crashHandler.init(getApplicationContext());
		initImageLoader(app);

	}

	public static App getContext() {
		return app;
	}

	public String getHW() {
		DisplayMetrics dm = getResources().getDisplayMetrics();
		int width = dm.widthPixels;// 宽度
		int height = dm.heightPixels;//
		return width + "*" + height;
	}

	public String getAPNType() {
		String netType = "unknown";
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		System.out.println("networkInfo.getExtraInfo() is " + networkInfo.getExtraInfo());
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
				netType = "CMNET";
			} else {
				netType = "CMWAP";
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = "WIFI";
		}
		return netType;
	}

	public String getUDID() {
		if (UDID == null) {
			synchronized (this) {
				if (UDID == null) {
					final SharedPreferences prefs = getSharedPreferences(PREFS_FILE, 0);
					final String id = prefs.getString(PREFS_DEVICE_ID, null);
					if (id != null) {
						// Use the ids previously computed and stored in the
						// prefs file
						UDID = id;
					} else {

						final String androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

						// Use the Android ID unless it's broken, in which case
						// fallback on deviceId,
						// unless it's not available, then fallback on a random
						// number which we store
						// to a prefs file
						try {
							if (!"9774d56d682e549c".equals(androidId)) {
								UDID = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
							} else {
								final String deviceId = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
								UDID = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
							}
						} catch (UnsupportedEncodingException e) {
							throw new RuntimeException(e);
						}
						// Write the value out to the prefs file
						prefs.edit().putString(PREFS_DEVICE_ID, UDID).commit();
					}
				}
			}
		}
		return UDID;
	}

	/**
	 * 初始化ImageLoader
	 * 
	 * @param context
	 */
	public void initImageLoader(Context context) {
		ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator()).memoryCache(new WeakMemoryCache()).diskCacheSize(1024 * 1024 * 1024)// 1G
				.tasksProcessingOrder(QueueProcessingType.LIFO);
		builder.diskCache(new UnlimitedDiscCache(new File(SDcardUtil.getPicDir())));
		// 如果是调试模式，输出日志，否则不输出
		if (BuildConfig.DEBUG) {
			builder.writeDebugLogs();
		}
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(builder.build());
	}

	public HashMap<String, Object> getAppCache() {
		return appCache;
	}

	private Timer mTimer = new Timer(true);
	private TimerTask mTimerTask;
	private TimerTask mSettingUpdate;

	public void startTask() {
		mTimerTask = new TimerTask() {

			@Override
			public void run() {
				GatherDataLogic.getInstance().getRealData();
			}
		};
		mSettingUpdate = new TimerTask() {
			public void run() {
				LoginLogic.getInstance().getAlarm(new OnHandlerResponse() {
					public void handlerResponse(int action, int code, Object... obj) {

					}
				});
			}
		};
		mTimer.schedule(mTimerTask, 10, 60 * 1000);
		mTimer.schedule(mSettingUpdate, 0, 60 * 60 * 1000);
	}

	public void destroyTask() {
		LogF.d(TAG, "destroyTask");
		while (mTimerTask != null && !mTimerTask.cancel())
			mTimer.cancel();
		mTimerTask = null;
	}

	public void showNotification(String title, String content) {
		Intent intent = new Intent();
		intent.setClass(this, StartActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		Notification notification = new NotificationCompat.Builder(this).setTicker(title).setContentTitle(title).setContentText(content)
				.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)).setSmallIcon(R.drawable.icon).setAutoCancel(true).setWhen(System.currentTimeMillis())
				.setContentIntent(pendingIntent).build();
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		nm.notify(9910248, notification);
	}

}
